//!公共的token
localStorage.setItem("token","eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyaW5mbyI6eyJpZCI6IjEiLCJsb2dpbl9uYW1lIjoiYWRtaW4iLCJwYXNzd29yZCI6Ijk2ZTc5MjE4OTY1ZWI3MmM5MmE1NDlkZDVhMzMwMTEyIiwibmFtZSI6IlRoaW5rSlPkuIDlk6UiLCJlbWFpbCI6Imhld3UxMTIyQDE2My5jb20iLCJwaG9uZSI6IjE3MzQyMDY1OTA5IiwibG9naW5faXAiOiI6OjEiLCJsb2dpbl9kYXRlIjoiMjAxOC0wMS0wOCAxNjoyMjo1MSIsImNyZWF0ZV9kYXRlIjoiMjAxNy0xMi0xNCAxMTo1Mjo0NiIsInVwZGF0ZV9kYXRlIjoiMjAyMS0wOS0wOCAxOTo0MzowMyIsImRlbF9mbGFnIjoiMCIsInJvbGVfaWQiOlsiMWM1NGUwMDNjMWZjNGRjZDliMDg3ZWY4ZDQ4YWJhYzMiXSwic3RhdHVzIjoxLCJyb2xlbmFtZSI6WyLotoXnuqfnrqHnkIblkZgiXX0sImlhdCI6MTYzNTQyNzI3N30.OJRBoPFCVMXUfmIreUqw9CVXqC4B-CcDB_uYl6omcO0")
let token= localStorage.getItem("token");

// 解决select框的渲染的问题
layui.use('form', function(){
    var form = layui.form; //只有执行了这一步，部分表单元素才会自动修饰成功
    form.render();
 });
  // 渲染分页
    let q = {
        login_name:$("#account").val(),
        page:1,
        limit:10,
        status:$("#state").val(),
        phone:$("#phone").val(),
    }
  function getRoleAdminList(){
    let token= localStorage.getItem("token");
    // console.log(token);
    axios({
        url:"http://124.223.14.236:8060/admin/sys_user/list",
        method:'get',
        headers: {
            "x-token": token,
        },
        params:q,
    })

    .then(res=>{
        var form = layui.form;
        form.render();
        let new_arr = res.data.data.data.map((item,value) => {
            return `
            <tr>
                <td>${value+1}</td>
                <td>${item.login_name}</td>
                <td>${item.name}</td>
                <td>${item.email}</td>
                <td>${item.phone}</td>
                <td>${item.rolename.join(" ")}</td>
                <td>${item.create_date}</td>
                <td>
                    <form class="layui-form" action="">
                        <div class="layui-input-block" >
                            <span style="display: inline-block;">警用</span>
                            <input type="checkbox" name="switch" lay-skin="switch" id="status_check" data-status="${item.status}" data-id="${item.value}"> 
                            <span style="display: inline-block;">启用</span>
                        </div>
                    </form>
                </td>
                <td align="center">
                    <!-- 按钮 -->
                    <button  type="button" class="layui-btn layui-btn-radius layui-btn layui-btn-normal" id="edit_user">
                        <i data-id=${item.id} class="layui-icon layui-icon-edit layui-font-12"></i>
                    </button>
                    <button 
                    id="del_user"
                    data-id="${value+1}"
                    type="button" 
                    class="layui-btn layui-btn layui-btn-radius layui-btn-danger">
                        <i data-id="${item.id}" class="layui-icon layui-icon-delete layui-font-12"></i>
                    </button>
                </td>
            </tr>
          
            ` 
        })
        $("tbody").html(new_arr.join(""));
        var form = layui.form;
        // 一般当表单存在动态生成时，进行渲染
        form.render();
        // 调用渲染
        status_show();

        layui.use('laypage', function(){
            var laypage = layui.laypage;
            
            //执行一个laypage实例
            laypage.render({
                elem: 'pageBox' //注意，这里的 test1 是 ID，不用加 # 号
                ,count: res.data.data.count //数据总数，从服务端得到
                ,layout:['count','limit','prev','page','next','skip'],
                limit: q.limit,
                curr: res.data.data.currentPage,
                limits:[10,20,40,50,100]
                ,jump: function(obj, first){
                //obj包含了当前分页的所有参数，比如：
                // console.log(obj.curr); //得到当前页，以便向服务端请求对应页的数据。
                        // console.log(obj.limit); //得到每页显示的条数
                
                //首次不执行
                if(!first){
                    q.page  = obj.curr
                    q.limit = obj.limit;
                    getRoleAdminList();
                }
                }
            });
        });
          
          q = {
            login_name:$("#account").val(),
            page:1,
            limit:10,
            status:$("#state").val(),
            phone:$("#phone").val(),
        }
    })
}

getRoleAdminList();



function click_status() {
    let statusAll = document.querySelectorAll("#status_check");
    for(let i = 0; i < statusAll.length; i++ ){
        if(statusAll[i].dataset.status === "1"){
            statusAll[i].checked = true;
            $(statusAll[i]).next().toggleClass("layui-form-onswitch");
        }else{
            console.log(000);
            statusAll[i].checked = false;
        }
    }
}

//------------------------渲染状态--------------------------------
function status_show() {

    let statusAll = document.querySelectorAll("#status_check");
    for(let i = 0; i < statusAll.length; i++ ){
        if(statusAll[i].dataset.status === "1"){
            statusAll[i].checked = true;
            $(statusAll[i]).next().toggleClass("layui-form-onswitch");
        }else{
            statusAll[i].checked = false;
        }
    }

}


//------------------------删除类容-------------------------------
// 删除类容
 function del(id){

    axios({
        url:"http://124.223.14.236:8060/admin/sys_user/del",
        method:'get',
        headers: {
            "x-token": token,
        },
        params:{
            id: id,
        }
    })
    .then(res=>{
        console.log(res.status);    
        if(res.status ===200){

            layer.close(layer.index);
            layer.msg('删除成功');
            getRoleAdminList();  

            // if(Math.ceil(total /q.limit) === q.page && article_list.length ===1){
            //     q.pagenum--
            // }      
        }
        

})

}

$("tbody").on("click","#del_user",function(e){
        console.log(111);
         let id =   e.target.dataset.id
         layer.open({
            content:'确认删除',
            btn:['确定','取消'],
                yes: function(index,layero){
                    del(id);
                },

                btn2: function(index,layero){
                }
        })
    
})

// -----------------------------------------------------------------
// 当查询按钮被点击的时候触发 select()方法
function select() {
    axios({
        url:"http://124.223.14.236:8060/admin/sys_user/list",
        method:'get',
        headers: {
            "x-token": token,
        },
        // params:{
        //     login_name:$("#account").val(),
        //     status:$("#state").val(),
        //     phone:$("#phone").val(),
        //     page:1,
        //     limit: 10,

        // }  
        params:q,
    })
    .then(res=>{
        console.log(res);    
        if(res.status ===200){
            getRoleAdminList();
            $("#account").val() ="";
            $("#state").val() = "";
            $("#phone").val() = "";
        }
        q= {};
    })
}


$("#select").on("click",function(){
        q.login_name = $("#account").val()
        q.status = $("#state").val(),
        q.phone = $("#phone").val(),
        select();
})

// -----------------------------------------------------------------
// 重置

$("#reset").on("click",function(){
    $("#account").val() ="";
    $("#state").val() = "";
    $("#phone").val() = "";
})


// -----------------------------------------------------------------
// 新增类容


function insert_input() {
    axios({
        url:"http://124.223.14.236:8060/admin/sys_role/list",
        method:'get',
        headers: {
            "x-token": token,
        },
        params:g,
    })
    .then(res=>{
    
        let input_new = res.data.data.data.map((item,value) => {
            return `
            <input type="checkbox" data-id="${item.id}" name="like[write]" title="${item.name}" class="select_input" value="${item.name}">
            `
        })
    
        $("#same_user_show").html(input_new.join(""))
        var form = layui.form;
    // 一般当表单存在动态生成时，进行渲染
        form.render();
    
    })
}

$("#newAdd").on("click",function(){
    insert_input();
    layer.open({
        type:1,
        title:"添加管理员",
        area: ['800px', '400px'],
        content: $('#add_form'),
        scrollbar: false,
        // content: ['http://sentsin.com', 'no'],
        btn:['确定','取消'],
        yes: function(index,layero){
            let chekALL = [];
            var new_checkALL  = document.querySelectorAll(".select_input");
            for(let i = 0; i< new_checkALL.length;i++){
                if(Number(new_checkALL[i].checked) === 1){
                    chekALL.push(new_checkALL[i].dataset.id);
                }
            }
            // 请求体需要的对象
            let reBody = {
                name: $("#name_account").val(),
                login_name: $("#username").val(),
                password: $("#password").val(),
                email: $("#email").val(),
                phone: $("#admin_phone").val(),
                role_id: chekALL,
                status: Number(document.querySelector("#check_status").checked),
            }

            add(reBody);
        },
        btn2: function(index,layero){
        }
    })
    var form = layui.form;
    // 一般当表单存在动态生成时，进行渲染
    form.render();
    })

function add(reBody) {
    axios({
        url:"http://124.223.14.236:8060/admin/sys_user/add",
        method:'post',
        headers: {
            "x-token": token,
        },
        data: reBody,
    })
    .then(res=>{
        console.log(res);    
        if(res.status === 200){
            layer.close(layer.index);
            layer.msg('添加成功');
            getRoleAdminList();  

        }
})
}


// 修改类容---------------------------------------------

let g = {
    page:1,
    limit:10,
   
}

    $("tbody").on("click","#edit_user",function(e){
        insert_input();
        console.log("插入完了");
        let id =   e.target.dataset.id
        layer.open({
            type:1,
            title:"编辑管理员",
            area: ['800px', '400px'],
            content: $('#add_form'),
            btn:['确定','取消'],
            yes: function(index,layero){
                // 遍历被选中的角色状态
                let chekALL = [];
                var new_checkALL  = document.querySelectorAll(".select_input");
                for(let i = 0; i< new_checkALL.length;i++){
                    if(Number(new_checkALL[i].checked) === 1){
                        chekALL.push(new_checkALL[i].dataset.id);
                    }
                }
                let reBody_Edit = {
                    name: $("#name_account").val(),
                    login_name: $("#username").val(),
                    password: $("#password").val(),
                    email: $("#email").val(),
                    phone: $("#admin_phone").val(),
                    role_id: chekALL,
                    id: id,
                    status: Number(document.querySelector("#check_status").checked),
                }

                edit(reBody_Edit);
            },

            btn2: function(index,layero){
            }
        })
        var form = layui.form;
        // 一般当表单存在动态生成时，进行渲染
        form.render();

    })

    function edit(reBody_Edit) {
        axios({
            url:"http://124.223.14.236:8060/admin/sys_user/update",
            method:'post',
            headers: {
                "x-token": token,
            },
            data: reBody_Edit,
        })
        .then(res=>{
            console.log(res.status);    
            if(res.status === 200){
                layer.close(layer.index);
                layer.msg('编辑成功');
                getRoleAdminList();  
            }
    })
    }




    